package process

import (
	"encoding/json"
	"fmt"
	commonmodel "helloword01/31chatroom/common/model"
	"helloword01/31chatroom/common/utils"
	"net"
)

type SmsProcess struct {
}

// SendGroupMes
//
//	@Description: 转发收到的群消息
//	@receiver this
//	@param mes
//	@return {}
func (this *SmsProcess) SendGroupMes(mes *commonmodel.Message) {
	var smsMes commonmodel.SmsMes
	err := json.Unmarshal([]byte(mes.Data), &smsMes)
	if err != nil {
		fmt.Println("json.Unmarshal fail =", err.Error())
		return
	}
	data, err := json.Marshal(mes)
	if err != nil {
		fmt.Println("json.Unmarshal fail =", err.Error())
		return
	}
	for id, up := range MyUserMgr.OnlineUsers {
		if id == smsMes.UserId {
			//continue 群发消息自己也可以收到！！！
		}
		this.SendMesToEachOnlineUser(data, up.Conn)
	}

}

// SendMesToEachOnlineUser
//
//	@Description: 发送个某个人
//	@receiver this
//	@param data
//	@param conn
func (this *SmsProcess) SendMesToEachOnlineUser(data []byte, conn net.Conn) {
	tf := &utils.Transfer{
		Conn: conn,
	}
	err := tf.WritePkg(data)
	if err != nil {
		fmt.Println("json.Unmarshal fail =", err.Error())
		return
	}
}

// SendPrivateMes
//
//	@Description:转发私信
//	@receiver this
//	@param mes
func (this *SmsProcess) SendPrivateMes(mes *commonmodel.Message) {
	var smsMes commonmodel.SmsPrivateMes
	err := json.Unmarshal([]byte(mes.Data), &smsMes)
	if err != nil {
		fmt.Println("json.Unmarshal fail =", err.Error())
		return
	}
	//对方不在线，消息返回
	toUserId := smsMes.ToUserId
	up, err := MyUserMgr.GetOnlineUserById(toUserId)
	if err != nil {
		smsMes.Code = 500
		smsMes.Err = err.Error()
		marshal, _ := json.Marshal(smsMes)
		mes.Data = string(marshal)
		//消息返回给发送方
		data, err := json.Marshal(mes)
		if err != nil {
			fmt.Println("json.Unmarshal fail =", err.Error())
			return
		}
		userId := smsMes.User.UserId
		up, err := MyUserMgr.GetOnlineUserById(userId)
		if err == nil {
			this.SendMesToEachOnlineUser(data, up.Conn)
		}
	} else {
		//消息发送到指定方
		smsMes.Code = 200
		marshal, _ := json.Marshal(smsMes)
		mes.Data = string(marshal)
		data, err := json.Marshal(mes)
		if err != nil {
			fmt.Println("json.Unmarshal fail =", err.Error())
			return
		}
		this.SendMesToEachOnlineUser(data, up.Conn)
	}
}

// SendLogoutMes
//
//	@Description: 发送退出消息
//	@receiver this
//	@param mes
func (this *SmsProcess) SendLogoutMes(mes *commonmodel.Message) {
	var logoutMes commonmodel.LogoutMes
	err := json.Unmarshal([]byte(mes.Data), &logoutMes)
	if err != nil {
		fmt.Println("json.Unmarshal fail =", err.Error())
		return
	}
	data, err := json.Marshal(mes)
	if err != nil {
		fmt.Println("json.Unmarshal fail =", err.Error())
		return
	}
	//删除在线用户
	MyUserMgr.DeleteOnlineUser(logoutMes.UserId)
	for _, up := range MyUserMgr.OnlineUsers {
		this.SendMesToEachOnlineUser(data, up.Conn)
	}
}
